package com.stockz.ui.swing.charting.widget;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.stockz.core.manager.ScripManager;
import com.stockz.core.model.Scrip;
import com.stockz.ui.swing.charting.view.StockChartView;
import com.stockz.ui.swing.core.MainFrame;
import com.stockz.ui.swing.core.menu.NewMenu;
import com.stockz.ui.swing.widget.JMenuItem;

@Component  
public class ChartMenuItem extends JMenuItem implements ActionListener, InitializingBean {
	private static final long serialVersionUID = 9116851577311615951L;

	@Autowired
	private NewMenu newMenu;
	@Autowired
	private ScripManager scripManager;
	
	public ChartMenuItem() {
		super("Chart",KeyEvent.VK_C,ActionEvent.ALT_MASK,"chart.png");
		addActionListener(this);
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		newMenu.add(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		List<Scrip> scripList = scripManager.getAllScrip("Q"); 
		Collections.sort(scripList, new Comparator<Scrip>(){
			@Override
			public int compare(Scrip o1, Scrip o2) {
				if(o1 != null && o2 != null && StringUtils.hasText(o1.getName()) && StringUtils.hasText(o2.getName())){
					return o1.getName().compareToIgnoreCase(o2.getName());
				}
				return 0;
			}
		});
		StockChartView stockChartView = new StockChartView(scripList);
		MainFrame.getInstance().add(stockChartView);
	}
}
